<template>
  <div>
    <el-form :model="queryParams" inline size="small">
      <el-form-item>
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户名"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <unit-select
          v-model="queryParams.unitId"
          :permission="listPermission"
          placeholder="请选择组织单位"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.state"
          clearable
          placeholder="请选择激活状态"
        >
          <el-option label="激活" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.isAdmin"
          clearable
          placeholder="请选择是否系统管理员"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getInfo" icon="Search">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="reset" icon="RefreshRight">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-between items-center mb-4">
      <div>
        <PermissionGuard :permission="addPermission">
          <el-button
            type="primary"
            icon="Plus"
            size="small"
            @click="userDialog.show()"
          >
            新增
          </el-button>
        </PermissionGuard>
        <PermissionGuard :permission="delPermission">
          <el-button
            type="danger"
            icon="Delete"
            size="small"
            :disabled="haveDeleteData"
            @click="handleDelete"
          >
            停用
          </el-button>
        </PermissionGuard>
      </div>
    </div>
    <Table :data="tableData" @selectionChange="handleSelectionChange">
      <TableColumn
        label="编号"
        prop="id"
        :min-width="getColumnWidth(tableData, 'id', 55)"
      />
      <TableColumn
        label="账号"
        prop="userName"
        :min-width="getColumnWidth(tableData, 'userName', 80)"
      />
      <TableColumn
        label="用户名"
        prop="name"
        :min-width="getColumnWidth(tableData, 'name', 80)"
      />
      <TableColumn
        label="所属组织单位"
        prop="unitName"
        :min-width="getColumnWidth(tableData, 'unitName', 120)"
      />
      <TableColumn
        label="手机号"
        prop="phone"
        :min-width="getColumnWidth(tableData, 'phone', 120)"
      />
      <TableColumn label="激活状态" :min-width="80">
        <template #default="{ row }">
          {{ row.state === 0 ? '激活' : '停用' }}
        </template>
      </TableColumn>
      <TableColumn label="创建时间" prop="createTime" :min-width="160" />
      <TableColumn label="更新时间" prop="updateTime" :min-width="160" />
      <TableColumn label="操作" fixed="right" :width="240">
        <template #default="{ row }">
          <PermissionGuard :permission="addPermission" :unit-id="row.unitId">
            <el-button
              type="primary"
              size="small"
              @click="userDialog.show(row)"
            >
              编辑
            </el-button>
          </PermissionGuard>
          <PermissionGuard
            :permission="resetPasswordPermission"
            :unit-id="row.unitId"
          >
            <el-button
              type="warning"
              size="small"
              @click="handleResetPassword(row.id)"
            >
              重置密码
            </el-button>
          </PermissionGuard>
          <PermissionGuard :permission="delPermission" :unit-id="row.unitId">
            <el-button
              v-if="row.state === 0"
              type="danger"
              size="small"
              @click="handleActiveOrStop(row.id, 1)"
            >
              停用
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              @click="handleActiveOrStop(row.id, 0)"
            >
              激活
            </el-button>
          </PermissionGuard>
        </template>
      </TableColumn>
    </Table>
    <Pagination
      v-model:current-page="page.currentPage"
      v-model:page-size="page.pageSize"
      :total="page.total"
      @size-change="getInfo"
      @current-change="getInfo"
    />
    <UserDialog ref="userDialog" @update="getInfo" />
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, useTemplateRef } from 'vue'
import {
  activeUserInfo,
  deleteUserInfo,
  getAllUserInfo,
  resetPassword,
} from '@/api/sys/userManage'
import Pagination, { PageType } from '@/components/Pagination.vue'
import { PageParam } from '@/type'
import UserDialog from '@/views/sys/user/UserDialog.vue'
import { ElMessageBox } from 'element-plus'
import Table from '@/components/table/Table.vue'
import TableColumn from '@/components/table/TableColumn.vue'
import UnitSelect from '@/components/unit/UnitSelect.vue'
import { getColumnWidth } from '@/plugins/util'
import useUserStore from '@/stores/user'
import PermissionGuard from '@/components/dataPermission/PermissionGuard.vue'
import { Message } from '@/hooks/message'

const listPermission = 'user:list'
const addPermission = 'user:add'
const delPermission = 'user:del'
const resetPasswordPermission = 'user:reset'

const userDialog = useTemplateRef<InstanceType<typeof UserDialog>>('userDialog')

const userStore = useUserStore()

const page = reactive<PageType>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
})

const queryParams = reactive({
  userName: undefined,
  name: undefined,
  unitId: undefined,
  phone: undefined,
  state: undefined,
  isAdmin: undefined,
})

const selectData = ref<any[]>([])
const tableData = ref<any[]>([])

function handleSelectionChange(val: any[]) {
  selectData.value = val
}

function handleDelete() {
  ElMessageBox.confirm(`确定停用${selectData.value.length}个用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const ids = selectData.value.map((item) => item.id).join(',')
      const { data } = await deleteUserInfo(ids)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        await getInfo()
      }
    })
    .catch(() => {})
}

const haveDeleteData = computed(() => {
  if (selectData.value.length === 0) {
    return true
  } else if (selectData.value.some((row) => row.state !== 0)) {
    return true
  } else {
    const ids = userStore.getPermissionId(delPermission)
    return (
      !userStore.isAdmin &&
      selectData.value.some((row) => !ids.includes(row.unitId))
    )
  }
})

async function reset() {
  Object.assign(queryParams, {
    userName: undefined,
    name: undefined,
    unitId: undefined,
    phone: undefined,
    state: undefined,
    isAdmin: undefined,
  })
  await getInfo()
}

function handleResetPassword(id: number) {
  ElMessageBox.confirm('确定重置该用户密码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const { data } = await resetPassword(id)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        await getInfo()
      }
    })
    .catch(() => {})
}

function handleActiveOrStop(id: number, type: 0 | 1) {
  if (type === 0) {
    ElMessageBox.confirm('确定激活该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(async () => {
        const { data } = await activeUserInfo(id)
        if (data.status === 200) {
          Message({
            message: data.message,
            type: 'success',
          })
          await getInfo()
        }
      })
      .catch(() => {})
  } else {
    ElMessageBox.confirm('确定停用该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(async () => {
        const { data } = await deleteUserInfo(id)
        if (data.status === 200) {
          Message({
            message: data.message,
            type: 'success',
          })
          await getInfo()
        }
      })
      .catch(() => {})
  }
}

async function getInfo() {
  const postParams = {
    userName: queryParams.userName,
    name: queryParams.name,
    unitId:
      queryParams.unitId || userStore.getPermissionId(listPermission).join(','),
    phone: queryParams.phone,
    state: queryParams.state,
    isAdmin: queryParams.isAdmin,
  }
  const postData: PageParam<typeof postParams> = {
    currentPage: page.currentPage,
    pageSize: page.pageSize,
    sort: [],
    query: postParams,
  }
  const { data } = await getAllUserInfo(postData)
  if (data.status === 200) {
    tableData.value = []
    page.currentPage = data.data.currentPage
    page.pageSize = data.data.pageSize
    page.total = data.data.totalCount
    tableData.value = data.data.data
  }
}

onMounted(async () => {
  await getInfo()
})
</script>

<style scoped></style>
